package office.stock.security.services;

import javax.ejb.EJB;
import javax.ejb.Stateless;

import office.stock.model.User;
import office.stock.persistance.UserDAO;

//TODO replace with proper service that uses LDAP
@Stateless
public class LoginServiceMock implements LoginService {

    @EJB
    private UserDAO userDAO;

    @Override
    public boolean areCredentialsValid(String username, String password) {
	return username != null && username.equals(password);
    }

    @Override
    public User getUserByCredentials(String username, String password) {
	User user = null;
	if (areCreadentialsValid(username, password)) {
	    user = ensureUserIsStored(username);
	}
	return user;
    }

    private boolean areCreadentialsValid(String username, String password) {
	return username != null && !username.isEmpty() && username.equals(password);
    }

    private User ensureUserIsStored(String username) {
	User user = userDAO.getByEmail(username);
	if (user == null) {
	    user = new User(username);
	    userDAO.persist(user);
	}
	return user;
    }
}
